package LeetCode刷题;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @program: Java_Study
 * @author: Xiaofan
 * @createTime: 2021-11-10 16:30
 * @description: Functions of this class is
 * 官方题解：class Solution {
 *     public int[] twoSum(int[] nums, int target) {
 *         Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
 *         for (int i = 0; i < nums.length; ++i) {
 *             if (hashtable.containsKey(target - nums[i])) {
 *                 return new int[]{hashtable.get(target - nums[i]), i};
 *             }
 *             hashtable.put(nums[i], i);
 *         }
 *         return new int[0];
 *     }
 * }
 **/
public class 两数之和 {
    public static void main(String args[]){

    }
    public static int[] twoSum(int[] nums, int target) {
        //我的做法比较与官方题解，其实就是先找target-nums[i],还是先找nums[i]的区别
        int len=nums.length;
        HashSet<Integer>set=new HashSet<Integer>();
        int ans1=0;
        int ans2=0;
        for(int num:nums){
            set.add(num);
        }
        for(int i=0;i<len;i++){
            int num=target-nums[i];
            if(set.contains(num)){
                for(int j=i+1;j<len;j++){
                    if(nums[j]==num){
                        return new int[]{i,j};
                    }
                }
            }
        }
        return null;
    }
}